package com.example.himalaya.view.activity;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import com.example.himalaya.R;
import com.example.himalaya.view.adapters.MainIndicatorAdapter;
import com.example.himalaya.view.adapters.MainContentAdapter;
import com.example.himalaya.view.callback.IPlayerViewCallback;
import com.example.himalaya.view.callback.ISobPopViewCallback;
import com.example.himalaya.presenters.PlayerPresenter;
import com.example.himalaya.presenters.RecommendPresenter;
import com.example.himalaya.constants.Constants;
import com.example.himalaya.utils.LogUtil;
import com.example.himalaya.view_component.RoundRectImageView;
import com.example.himalaya.view_component.SobPopWindow;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;

import java.util.List;

public class MainActivity extends FragmentActivity implements IPlayerViewCallback, ISobPopViewCallback {

    // Constance
    private static final String TAG = "MainActivity";

    // UI object
    private ViewPager mMainPager;
    private TextView mHeaderTitle;
    private TextView mSubTitle;
    private ImageView mPlayControl;

    private ImageView mPlayList;

    private View mPlayControlItem;
    private View mSearchBtn;

    // Other UI Object
    private SobPopWindow mSobPopWindow;
    private RoundRectImageView mRoundRectImageView;
    protected MagicIndicator mMainIndicator;

    // Logic object
    private PlayerPresenter mPlayerPresenter;

    // Animator object
    public ValueAnimator mEnterBgAnimator;
    public ValueAnimator mOutBgAnimator;

    // Adapter
    private MainIndicatorAdapter mMainIndicatorAdapter;
    private CommonNavigator mCommonNavigator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initVariable();

        initPresenter();

        initAdapter();

        initListener();

        initBgAnimation();

        initView();
    }

    private void initAdapter() {
        // 创建对象
        // 创建一个indicator的适配器
        mMainIndicatorAdapter = new MainIndicatorAdapter(this);

        mCommonNavigator = new CommonNavigator(this);
        mCommonNavigator.setAdapter(mMainIndicatorAdapter);

        // 设置要显示的内容

        // 创建内容设配器
        FragmentManager fragmentManager = getSupportFragmentManager();
        MainContentAdapter mainContentAdapter = new MainContentAdapter(fragmentManager);

        // 初始化
        mMainPager.setAdapter(mainContentAdapter);
    }

    private void initVariable() {
        // UI Object
        mRoundRectImageView = this.findViewById(R.id.main_track_cover);
        mHeaderTitle = this.findViewById(R.id.main_head_title);
        mSubTitle = this.findViewById(R.id.main_sub_title);
        mPlayControl = this.findViewById(R.id.main_play_control);
        mPlayList = this.findViewById(R.id.main_player_list);
        mPlayControlItem = this.findViewById(R.id.main_play_control_item);
        mMainPager = this.findViewById(R.id.main_pager);
        mSearchBtn = this.findViewById(R.id.main_search_btn);

        // Other UI object
        mMainIndicator = this.findViewById(R.id.main_indicator);
        mMainIndicator.setBackgroundColor(this.getResources().getColor(R.color.color_main));
        // 弹出的音乐列表
        mSobPopWindow = SobPopWindow.getInstance();

    }

    // 场景动画对象的方法
    private void initBgAnimation() {
        // 设置动画值变化的范围
        mEnterBgAnimator = ValueAnimator.ofFloat(1.0f, 0.7f);
        // 变换时间
        mEnterBgAnimator.setDuration(Constants.BG_ANIMATION_DURATION);
        mEnterBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                // LogUtil.d(TAG, "value -->" + valueAnimator.getAnimatedValue());
                // 获取动画模块计算出了当前alpha值
                float value = (float) valueAnimator.getAnimatedValue();
                // 跟新UI
                updateBgAlpha(value);
            }
        });

        mOutBgAnimator = ValueAnimator.ofFloat(0.7f, 1.0f);
        mOutBgAnimator.setDuration(Constants.BG_ANIMATION_DURATION);
        mOutBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                // LogUtil.d(TAG, "value -->" + valueAnimator.getAnimatedValue());
                // 获取动画模块计算出了当前alpha值
                float value = (float) valueAnimator.getAnimatedValue();
                // 跟新UI
                updateBgAlpha(value);
            }
        });
    }

    private void initPresenter() {
        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
        mPlayerPresenter.registerViewCallback(this);
        mSobPopWindow.registerViewCallback(this);
    }

    private void initView() {

        // 把ViewPager和Indicator绑定到一起
        // 自动平分顶部
        mCommonNavigator.setAdjustMode(true);
        mMainIndicator.setNavigator(mCommonNavigator);
        ViewPagerHelper.bind(mMainIndicator, mMainPager);

        // 标题跑马灯
        mHeaderTitle.setSelected(true);
    }

    private void initListener() {
        // 点击标签的事件
        mMainIndicatorAdapter.setOnIndicatorTapClickListener(new MainIndicatorAdapter.OnIndicatorTapClickListener() {
            @Override
            public void onTabClick(int index) {
                LogUtil.d(TAG, "Click index is ->" + index);
                if (mMainPager != null) {
                    mMainPager.setCurrentItem(index);
                }
            }
        });

        // 播放暂停事件
        mPlayControl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (mPlayerPresenter != null) {
                    boolean hasPlayList = mPlayerPresenter.hasPlayList();

                    if (!hasPlayList) {
                        // 没有设置过播放列表, 我们就播放默认的第一个推荐专辑
                        playFirstRecommend();
                    } else {
                        if (mPlayerPresenter.isPlaying()) {
                            mPlayerPresenter.pause();
                        } else {
                            mPlayerPresenter.play();
                        }
                    }
                }
            }
        });

        mPlayList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // 显示播放列表

                if (mSobPopWindow.isReady) {

                    if (mSobPopWindow.isShowing()) {
                        mSobPopWindow.dismiss();
                    }

                    // 显示在底部
                    mSobPopWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);

                    // 修改背景的透明度有一个渐变的过程
                    mEnterBgAnimator.start();
                } else {
                    Toast.makeText(MainActivity.this, "当前还没有播放列表", Toast.LENGTH_LONG).show();
                }

            }
        });

        // // 当弹出的音乐列表消失的监听
        // mSobPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
        // @Override
        // public void onDismiss() {
        // // 需要恢复背景的透明度
        // mOutBgAnimator.start();
        // }
        // });

        mPlayControlItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean hasPlayList = mPlayerPresenter.hasPlayList();

                if (!hasPlayList) {
                    playFirstRecommend();
                }

                // 跳转到播放界面
                startActivity(new Intent(MainActivity.this, PlayerViewActivity.class));
            }
        });

        // 搜索按钮点击的事件
        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, SearchViewActivity.class);

                startActivity(intent);
            }
        });
    }

    /**
     * 播放第一个推荐的内容
     */
    private void playFirstRecommend() {
        List<Album> currentRecommend = RecommendPresenter.getInstance().getCurrentRecommend();

        if (currentRecommend != null && currentRecommend.size() > 0) {
            Album album = currentRecommend.get(0);
            long albumId = album.getId();

            mPlayerPresenter.playByAlblumId(albumId);
        }
    }

    public void updateBgAlpha(float alpha) {
        // 得到当前窗口
        Window window = this.getWindow();
        // 获取到窗口的属性
        WindowManager.LayoutParams attributes = window.getAttributes();
        // 修改属性
        attributes.alpha = alpha;
        // 刷新窗口的属性
        window.setAttributes(attributes);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mPlayerPresenter != null) {
            mPlayerPresenter.unRegisterViewCallback(this);
        }

        if (mMainIndicatorAdapter != null) {
            mMainIndicatorAdapter.setOnIndicatorTapClickListener(null);
        }

        if (mSobPopWindow != null) {
            mSobPopWindow.unRegisterViewCallback(this);
        }
    }

    @Override
    public void onPlayStart() {
        updatePlayControl(false);
    }

    @Override
    public void onPlayPause() {
        updatePlayControl(true);
    }

    @Override
    public void onPlayStop() {
        updatePlayControl(true);
    }

    private void updatePlayControl(boolean isPlay) {
        if (mPlayControl != null) {
            mPlayControl.setImageResource(isPlay ? R.drawable.selector_player_play : R.drawable.selector_player_pause);
        }
    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void nextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onListLoaded(List<Track> list) {

    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {

    }

    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAdFinished() {

    }

    @Override
    public void onProgressChange(int currPos, int total) {

    }

    @Override
    public void onTrackUpdate(Track track, int playIndex) {
        if (track != null) {
            String trackTitle = track.getTrackTitle();
            String nickname = track.getAnnouncer().getNickname();
            String coverUrlLarger = track.getCoverUrlLarge();

            LogUtil.d(TAG, "trackTitle --> " + trackTitle);
            LogUtil.d(TAG, "nickname --> " + nickname);
            LogUtil.d(TAG, "coverUrlLarger --> " + coverUrlLarger);

            if (mHeaderTitle != null) {
                mHeaderTitle.setText(trackTitle);
            }

            if (mSubTitle != null) {
                mSubTitle.setText(nickname);
            }
            if (!TextUtils.isEmpty(coverUrlLarger)) {
                Picasso.with(this).load(coverUrlLarger).into(mRoundRectImageView);
            } else {
                mRoundRectImageView.setImageResource(R.mipmap.default_picture);
            }
        }
    }

    @Override
    public void updateListOrder(boolean isReverse) {

    }

    @Override
    public void SobPopOpen() {

    }

    @Override
    public void SobPopClose() {
        mOutBgAnimator.start();
    }
}
